/*
 * Copyright (C) 2011 Wojciech Dzierżanowski
 * See LICENSE.txt for licensing details.
 */

package wdzierzan.downstream.cli;

import java.io.Console;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.ParseException;

/**
 *
 * @author Wojciech Dzierżanowski <wojciech.dzierzanowski@gmail.com>
 */
class Source {

    private String username;
    private String hostname;
    private String path;

    protected Source() {
    }

    Source(CommandLine line) throws ParseException {
        parseCommandLine(line);
    }

    String getUsername() {
        return username != null
                ? username
                : System.getProperty("user.name", "anonymous");
    }

    String getPassword() {
        Console console = System.console();
        if (console == null)
            return "";

        return new String(console.readPassword("Enter password for %s@%s: ",
                getUsername(), getHostname()));
    }

    String getHostname() {
        try {
            return hostname != null
                    ? hostname
                    : InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException ex) {
            throw new RuntimeException(ex);
        }
    }

    String getPath() {
        return path;
    }

    private void parseCommandLine(CommandLine line) throws ParseException {

        username = null;
        hostname = null;
        path = null;

        String remotePath = line.getArgs()[0];
        int i = remotePath.lastIndexOf(':');
        path = remotePath.substring(i + 1, remotePath.length());
        if (path.isEmpty())
            throw new ParseException("Error parsing remote path");

        String userAndHost = remotePath.substring(0, Math.max(0, i));
        i = userAndHost.lastIndexOf('@');
        hostname = userAndHost.substring(i + 1, userAndHost.length());
        username = userAndHost.substring(0, Math.max(0, i));

        if (hostname.isEmpty())
            hostname = null;
        if (username.isEmpty())
            username = null;
    }
}
